//
//  GameMaster.m
//  DualSnake
//
//  Created by HacJune Lee on 13. 12. 10..
//  Copyright (c) 2013년 HakJune Lee. All rights reserved.
//

#import "GameMaster.h"

#define WALL_WIDTH 10;

@implementation GameMaster

static GameMaster * gameMaster = nil;

+(GameMaster*)shared
{
    if(gameMaster == nil)
    {
        gameMaster = [[GameMaster alloc]init];
        gameMaster.player1_nextDirection = -1;
        gameMaster.player2_nextDirection = -1;
    }
    
    return gameMaster;
}

-(int)getWallWith
{
    return WALL_WIDTH;
}

-(int)getGridCount
{
    return 10;
}

-(int)getSingleModePlayerStartGridNum
{
    return 20;
}

-(int)getInputDirectionWithSnakeTag:(int)tag
{
    if(tag == 0)
    {
        return _player1_nextDirection;
    }
    else if(tag == 1)
    {
        return _player2_nextDirection;
    }
    else
    {
        return 0;
    }
    
}

-(float)getGridWidth
{
    CGSize gridSize = [self getGridSize];
    int gridCount = [self getGridCount];
    
    float gridWidth = gridSize.width/gridCount; //그리드 한칸의 가로폭.
    
    return gridWidth;
}

-(int)getRandomItemType
{
    return 0;
}

-(CGSize)getGridSize
{
    int _wallWidth = [self getWallWith];
    float _screenWith = [self getDisplaySize].width;
    
    //벽의 폭을 제외한 실제 게임판.
    CGSize gridViewSize = CGSizeMake(_screenWith - (_wallWidth * 2), _screenWith - (_wallWidth * 2));
    return gridViewSize;
}

-(CGSize)getDisplaySize
{
    CGRect screenRect = [[UIScreen mainScreen] bounds];
    return screenRect.size;
}

-(void)setTimer
{
    playTimer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(playTime) userInfo:nil repeats:YES];
    
    [[NSRunLoop currentRunLoop] addTimer:playTimer forMode:NSDefaultRunLoopMode];
}

-(void)playTime
{
    playTimeCount++;
    [_delegate playTimeTic:playTimeCount];
    
    if((playTimeCount % 10) == 0)
    {
        [self createItem];
    }
}

-(void)createItem
{
    int itemType = [self getRandomItemType];
    [_delegate createItem:itemType];
}

-(void)checkItemRooting:(GameBlock*)gameblock
{
    
}


#pragma mark -
#pragma mark 그리드 넘버 변환식 좌표 -> 넘버
-(int)convertCGpointToGridNum:(CGPoint)point
{
    int _wallWidth = [self getWallWith];
    int _gridWidth = [self getGridSize].width;
    int _gridCount = [self getGridCount];
    
    int gridNumX = (int)((point.x - _wallWidth))/_gridWidth;
    int gridNumY = (int)((point.y - _wallWidth))/_gridWidth;
    
    int gridNum = (gridNumY * _gridCount) + gridNumX;
    
    return gridNum;
}

#pragma mark 그리드 넘버 변환식 넘버 -> 좌표
-(CGPoint)convertGridNumToCGPoing:(int)gridNum
{
    int _wallWidth = [self getWallWith];
    int _gridWidth = [self getGridWidth];
    int _gridCount = [self getGridCount];
    
    int pointX = (_gridWidth * (gridNum % _gridCount)) + _wallWidth;
    int pointY = (_gridWidth * (gridNum / _gridCount)) + _wallWidth;
    
    return CGPointMake(pointX, pointY);
}

@end
